package com.hengpeng.msls.controller;

import java.io.UnsupportedEncodingException;
import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.itfinbase.constants.SystemConfigConstants;
import com.hengpeng.itfinbase.constants.TransCodeConstants;
import com.hengpeng.itfinbase.message.userInfo.UserInfoResponse;
import com.hengpeng.itfinbase.message.userInfo.UserLoginRequest;
import com.hengpeng.itfinbase.persist.Partner;
import com.hengpeng.itfinbase.persist.Partner.PartnerType;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.msls.constants.LSConstants;
import com.hengpeng.msls.constants.SystemConfigUtil;
import com.hengpeng.msls.vo.SessionMember;

@Controller
public class LoginController extends BaseController
{
    @RequestMapping(value = "/login")
    @ResponseBody
    public ServiceResult<?> login(HttpServletRequest request, ModelMap map, String username, String password,
            String checkcode, String url, HttpServletResponse resp) throws Exception
    {
        if (username == null || username.trim().equals("")) {
            return validateFailure("必须输入手机号");
        }
        if (password == null || password.equals("")) {
            return validateFailure("必须输入登录密码");
        }
        UserLoginRequest userLoginRequest = new UserLoginRequest();
        userLoginRequest.setTransType(TransCodeConstants.MemberTransCode.MEMBER_LOGIN);
        userLoginRequest.setUsername(username);
        userLoginRequest.setPassword(password);
        userLoginRequest.setUserIpAddress(request.getRemoteAddr());
        UserInfoResponse response = (UserInfoResponse) serviceFactory.getProtFactory().remoteTrans(userLoginRequest);
        ServiceResult<UserInfo> sr = getServiceResult(response, UserInfo.class);
        sr.setReturnValue(response.getUserInfo());
        if (!sr.getIsSuccess()) {
            return sr;
        }
        SessionMember member = serviceFactory.getUserInfoService().refreshSessionUser(username);
        request.getSession().setAttribute(LSConstants.CLIENT_SESSION_MEMBER, member);
        Partner partner = serviceFactory.getPersistService().get(Partner.class,SystemConfigUtil.getConfigValue(SystemConfigConstants.PARTNER_ID));
        if (partner != null && !partner.getPartnerType().equals(PartnerType.FUND)) {
            member.setIsTrust(true);
        }
        if (url != null && !url.trim().equals("")) {
            try {
                sr.setMessage(java.net.URLDecoder.decode(url, "utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else {
            sr.setMessage(null);
        }
        System.out.println(getSessionMember(request).getUser().getId());
        /**
         * 读取cookie中登陆后前往的地址
         */
        String backurl = "";
        Cookie[] cookies = request.getCookies();
        for (Cookie c : cookies) {
            if ("backurl".equals(c.getName())) {
                backurl = c.getValue();
                break;
            }
        }
        if (!StringHelper.isEmpty(backurl)) {
            sr.setMessage(backurl);
        }
        /**
         * 删除返回地址
         */
        Cookie cookie = new Cookie("backurl",backurl);
        cookie.setMaxAge(0);
        resp.addCookie(cookie);
        return sr;
    }
    
    @RequestMapping(value = "/logout")
    public String loginout(HttpServletRequest request, HttpServletResponse response, ModelMap map)
    {
        SessionMember session = getSessionMember(request);
        if (session != null)
        {
            session.setIsLogin(false);
            UserInfo user = serviceFactory.getUserInfoService().getUserInfo(session.getUser().getUserName());
            map.put("endTime", new Date());
            map.put("loginTime", user.getLastLoginTime());
        }
        request.getSession().removeAttribute(LSConstants.CLIENT_SESSION_MEMBER);
        return "redirect:/index.htm";
    }
}
